package interfaceGrafica;

import criptografia.Encriptador;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import logica.main.MainGrafico;
import logica.pessoa.Agencia;
import logica.pessoa.Locador;
import logica.util.Data;
import persistencia.GeradorDeLogs;
import persistencia.MecanismoDePersistenciaSeguro;
import util.Constantes;
import util.Endereco;
import util.TipoDeLogradouro;
import util.UF;

/**
 * @author Equipe Localisa (Usa quem precisa!)
 */

@SuppressWarnings("serial")
public class InterfaceLogin extends javax.swing.JPanel {

    /**
	 * 
	 */
	
	private Agencia agencia;
    private static MecanismoDePersistenciaSeguro mecanismoDePersistenciaAgencia;
    private List<Locador> locadores;
    private static MecanismoDePersistenciaSeguro mecanismoDePersistenciaUsuarios;
    private static GeradorDeLogs geradorDeLog;
    private static Data hoje;
    private int tentaivasDeLogar;
    /** Creates new form InterfaceLogin */
    public InterfaceLogin() {
            hoje = new Data();
            initComponents();
            lerDados();
            atualizarDisplays();
            try {
                geradorDeLog = new GeradorDeLogs();
            } catch (Exception e) {
            }
            
            try {
				geradorDeLog.escreveLog("Programa inciado");
			} catch (Exception e) {
				
			}
            
            jButton1.setEnabled(false);
    }
    
    private void atualizarDisplays() {
        if (agencia != null) {
            jTextPane1.setText("Agencia " + agencia.getNomeFantasia() + "\n<" + hoje.getDataPorExtenso() + ">");
        }
    }

    @SuppressWarnings("unchecked")
	private void lerDados(){
        try{
            mecanismoDePersistenciaAgencia = new MecanismoDePersistenciaSeguro("arquivos/agencia.ser");
            agencia = (Agencia) mecanismoDePersistenciaAgencia.recuperaObjetoNoArquivo();
            mecanismoDePersistenciaUsuarios = new MecanismoDePersistenciaSeguro("arquivos/locadores.ser");
            locadores = (ArrayList<Locador>) mecanismoDePersistenciaUsuarios.recuperaDoArquivo();
            if(agencia == null){
            	agencia = getAgenciaDefault();
            }
            if(locadores == null){
            	locadores = new ArrayList<Locador>();
            }
            if ( locadores.isEmpty() ){
                locadores.add(getGerenteDefault());
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Houve um problema no carregamento do banco de dados do Sistema.", null, JOptionPane.ERROR_MESSAGE);
        }
    }

    private Agencia getAgenciaDefault(){
        Agencia defaults = null;
        try {
            defaults = new Agencia();
            defaults.setNomeFantasia("DEFAULT");
            defaults.setRazaoSocial("REPRESENTANTE DEFAULT");
            defaults.setTelefone("(83) 8888-8888");
            defaults.setEmail("default@default.com");
            defaults.setCNPJ("11111111111111");
            defaults.setInscricaoEstadual("111111111111");
            Endereco endereco = new Endereco();
            endereco.setTipoDeLogradouro(TipoDeLogradouro.Viaduto);
            endereco.setLogradouro("RUA DEFAULT");
            endereco.setNumero(1);
            endereco.setBairro("BAIRRO DEFAULT");
            endereco.setCidade("CIDADE DEFAULT");
            endereco.setEstado(UF.PB);
            endereco.setObs("OBS DEFAULT");
            endereco.setCep("58310000");
            defaults.setEndereco(endereco);
            return defaults;
        } catch (Exception e) {
        }
        return defaults;
    }

    private Locador getGerenteDefault() {
        Locador defaults = new Locador();
        try {
            defaults.setNome("ADMINISTRADOR DO SISTEMA");
            defaults.setTelefone("(83) 0000-0000");
            defaults.setEmail("admin@default.com");
            defaults.setCPF("00000000000");
            defaults.setRG("000000000");
            defaults.setDataDeNascimento(new Data(26,3,1992));
            defaults.setNaturalidade("Hardware");
            defaults.setLogin("admin");
            defaults.setSenha("admin");
            defaults.setEhGerente(true);
            Endereco endereco = new Endereco();
            endereco.setTipoDeLogradouro(TipoDeLogradouro.Viaduto);
            endereco.setLogradouro(", logo abaixo");
            endereco.setNumero(155);
            endereco.setBairro("Bairro Defaut");
            endereco.setCidade("Cidade Default");
            endereco.setEstado(UF.PB);
            endereco.setObs("");
            endereco.setCep("00000000");
            defaults.setEndereco(endereco);
        } catch (Exception e) {
        }
        return defaults;
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        jLabel1.setFont(new java.awt.Font("VL Gothic", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(9, 66, 236));
        jLabel1.setText("Sistema Localisa");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jPasswordField1.setText("");
        jPasswordField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPasswordField1MouseClicked(evt);
            }
        });
        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyPressed(evt);
            }
        });

        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField1MouseClicked(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jLabel3.setText("Senha:");

        jLabel2.setText("Login:");

        jButton1.setText("LOGAR");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Courier 10 Pitch", 1, 13));
        jLabel4.setText("Localisa, usa quem precisa!");

        jTextPane1.setBackground(new java.awt.Color(145, 135, 127));
        jTextPane1.setEditable(false);
        jTextPane1.setFont(new java.awt.Font("DejaVu Sans", 3, 13));
        jTextPane1.setText("Agencia");
        jScrollPane2.setViewportView(jTextPane1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(57, 57, 57)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPasswordField1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(109, 109, 109)
                        .addComponent(jButton1)))
                .addContainerGap(50, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(29, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addGap(29, 29, 29))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(9, 9, 9)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("deprecation")
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        Iterator<Locador> iterador = locadores.iterator();
        Locador locadorAtual = null;
	while(iterador.hasNext()){

            Locador locador = iterador.next();
           
            if(locador.getLogin().equals(jTextField1.getText())){

                Encriptador encriptor = new Encriptador();

                try {
                    if ( locador.getSenha().equals(encriptor.geraHashParaSenha(jPasswordField1.getText()))) {
                        locadorAtual = locador;
                        break;

                    }
                } catch (Exception e) {}
                
            }
        }
        if (locadorAtual == null) {
            tentaivasDeLogar++;
        	JOptionPane.showMessageDialog(null, "Login e/ou senha invalidos.", "Entrada nao permitida", JOptionPane.ERROR_MESSAGE);
            if(tentaivasDeLogar == 3){
            	try {
					geradorDeLog.escreveLog(" Ocorreram sucessivas tentativas de logar como o usuario  sem sucesso.");
				} catch (Exception e) {
					
				}
            }
        	
        } else {
            JOptionPane.showMessageDialog(null, "Bem vindo!", "Mensagem de entrada no sistema.", JOptionPane.PLAIN_MESSAGE);
            if ( locadorAtual.getEhGerente() ){
                MainGrafico.setMenuCorrente(new InterfaceMenuGerente());
                MainGrafico.setUsuarioLogado(locadorAtual);
                MainGrafico.entrarNaArea(MainGrafico.getMenuCorrente(), Constantes.INTERFACE_TAMANHO_MENU[0], Constantes.INTERFACE_TAMANHO_MENU[1]);
                MainGrafico.sairDaArea(this);
            }
            else{
                MainGrafico.setMenuCorrente(new InterfaceLogin());
                MainGrafico.setUsuarioLogado(locadorAtual);
                MainGrafico.entrarNaArea(new InterfaceLocacao(), Constantes.INTERFACE_TAMANHO_LOCACAO[0], Constantes.INTERFACE_TAMANHO_LOCACAO[1]);
                MainGrafico.sairDaArea(this);
            }
        }
        jTextField1.setText("");
        jPasswordField1.setText("");

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jPasswordField1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPasswordField1MouseClicked
        jPasswordField1.setText("");
    }//GEN-LAST:event_jPasswordField1MouseClicked

    private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyPressed
    }//GEN-LAST:event_jPasswordField1KeyPressed

    private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MouseClicked
    }//GEN-LAST:event_jTextField1MouseClicked

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        jButton1.setEnabled(true);
    }//GEN-LAST:event_jTextField1KeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

}
